define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'customer/package/index' + location.search,
                    add_url: 'customer/package/add/customer_id/' + Config['customer_id'],
                    edit_url: 'customer/package/edit',
                    del_url: 'customer/package/del',
                    multi_url: 'customer/package/multi',
                    import_url: 'customer/package/import',
                    table: 'customer_package',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'package_id',
                sortName: 'package_id',
                // fixedColumns: true,
                // fixedRightNumber: 1,
                queryParams: (params) => {
                    var filter = JSON.parse(params.filter)
                    var op = JSON.parse(params.op)

                    filter.customer_id = Config['customer_id']
                    op.customer_id = '='

                    params.filter = JSON.stringify(filter)
                    params.op = JSON.stringify(op)

                    return params
                },
                columns: [
                    [
                        {checkbox: true},
                        {field: 'package_id', title: __('ID')},
                        // {field: 'customer_id', title: __('Customer_id')},
                        {
                            field: 'status',
                            title: '审核状态',
                            formatter: Table.api.formatter.status,
                            custom: {1: "orange", 2: "green", 3: "red"},
                            searchList: {0: '未提交', 1: '审核中', 2: '审核通过', 3: '审核不通过'}
                        },

                        {
                            field: 'service_list',
                            title: '包含服务',
                            operate: false,
                            formatter: function (value, row, index) {
                                var str = ''
                                value.forEach((item) => {
                                    str += item.service_name + '(<span style="color: #9a1a1a">￥</span>' + item.deal_price + ')<br/>'
                                })
                                return str
                            }
                        },
// formatter: function (value, row, index) {
                        //     var str = ''
                        //     str += '标准金额：' + value.standard_price + '<br/>'
                        //     str += '成交金额：' + value.deal_price + '<br/>'
                        //     str += '成本金额：' + value.cost_price + '<br/>'
                        //     return str
                        // }
                        {
                            field: 'total_data.standard_price',
                            title: '标准价格',
                            operate: false,
                            formatter: Table.api.formatter.content
                        },
                        {
                            field: 'total_data.deal_price',
                            title: '成交价格',
                            operate: false,
                            formatter: Table.api.formatter.content
                        },
                        {
                            field: 'total_data.cost_price',
                            title: '成本价格',
                            operate: false,
                            formatter: Table.api.formatter.content
                        },
                        {
                            field: 'total_data.collection_price',
                            title: '已收款金额',
                            operate: false,
                            formatter: Table.api.formatter.content
                        },
                        {
                            field: 'total_data.balance_price',
                            title: '未收尾款',
                            operate: false,
                            formatter: Table.api.formatter.content
                        },

                        // {
                        //     field: 'signature_url',
                        //     title: __('Signature_url'),
                        //     operate: 'LIKE',
                        //     formatter: Table.api.formatter.url
                        // },
                        {
                            field: 'signature_time',
                            title: __('Signature_time'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },

                        {
                            field: 'contract_url',
                            title: __('电子合同'),
                            operate: false,

                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.buttons,
                            buttons: [
                                {
                                    name: 'addtabs',
                                    text: __('查看合同'),
                                    title: __('查看合同'),
                                    classname: 'btn btn-xs btn-warning btn-addtabs',
                                    url: 'customer/package/previewContract',
                                },
                                {
                                    name: 'addtabs',
                                    text: __('签订合同'),
                                    title: __('服务列表'),
                                    classname: 'btn btn-xs btn-warning btn-dialog',
                                    url: 'customer/package/signatureContract',
                                },
                            ]
                        },
                        {
                            field: 'create_time',
                            title: __('Create_time'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            buttons: [
                                {
                                    name: 'addtabs',
                                    text: __('提交审核'),
                                    title: __('提交审核'),
                                    url: 'customer/package/subreview',
                                    classname: 'btn btn-xs btn-success btn-magic btn-ajax',
                                    success: function (data, ret) {
                                        table.bootstrapTable('refresh');
                                    },
                                    error: function (data, ret) {
                                        console.log(data, ret);
                                        Layer.alert(ret.msg);
                                        return false;
                                    },
                                    visible: function (row) {
                                        if (row.status == 0 || row.status == 3) {
                                            return true
                                        } else {
                                            return false
                                        }
                                    },
                                },

                                // {
                                //     name: 'addtabs',
                                //     text: __('查看详情'),
                                //     title: __('查看详情'),
                                //     extend: 'data-area=\'["80%","80%"]\'',
                                //     classname: 'btn btn-xs btn-success btn-dialog',
                                //     url: 'customer/audit/details',
                                // },
                            ],
                            events: Table.api.events.operate,
                            // formatter: Table.api.formatter.operate
                            formatter: function (value, row, index) {
                                var that = $.extend({}, this);
                                var table = $(that.table).clone(true);
                                if (row.status == 0 || row.status == 2 || row.status == 3) {
                                    // return true
                                } else {
                                    $(table).data("operate-edit", null);
                                }
                                //隐藏编辑按钮

                                that.table = table;
                                return Table.api.formatter.operate.call(that, value, row, index);
                            }
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            const service = Config['service'] || []
            const types = [
                'gth',
                'xgmnsr',
                'ybnsr',
            ]
            $('#c-service').change((e) => {
                rendService()
            })

            function rendService() {
                const value = $('#c-service').val()
                const corporate_type = Config['customer']['corporate_type']
                var index = 0
                const field_name = 'serviceTable'
                var str = '<table border="1" width="100%" style="margin-top: 10px">'
                str += "<tr>"
                str += '<td>服务名称</td>'
                str += '<td>标准价格</td>'
                str += '<td>成交价格</td>'
                str += '<td>服务周期（月）</td>'
                str += '<td>本次收款</td>'
                str += '<td>剩余尾款</td>'
                str += "</tr>"
                service.forEach(item => {
                    if (value.includes(item.id.toString())) {
                        str += "<tr>"
                        str += '<td>' + item.service_name + '</td>'
                        str += '<td>￥' + item[types[corporate_type] + '_standard_price'] + '</td>'
                        str += '<td><input index="' + index + '" bs="' + index + '_deal_price" class="form-control deal_price_ks" value="' + item[types[corporate_type] + '_standard_price'] + '" name="row[' + field_name + '][' + index + '][deal_price]" placeholder="请输入成交价格" data-rule="required;" type="text"/></td>'
                        str += '<td><input index="' + index + '" bs="' + index + '_month" class="form-control" name="row[' + field_name + '][' + index + '][month]" placeholder="服务周期" data-rule="required" type="text"/></td>'
                        str += '<td><input index="' + index + '" bs="' + index + '_collection_price" class="form-control collection_price_ks" name="row[' + field_name + '][' + index + '][collection_price]" placeholder="本次收款" data-rule="required" type="text"/></td>'
                        str += '<td><input index="' + index + '" bs="' + index + '_balance_price" class="form-control balance_price_ks" name="row[' + field_name + '][' + index + '][balance_price]" placeholder="剩余尾款" data-rule="required" type="text"/></td>'
                        str += "</tr>"
                        str += '<input name="row[' + field_name + '][' + index + '][service_id]" value="' + item.id + '" type="hidden"/>'
                        str += '<input name="row[' + field_name + '][' + index + '][ledger_expenses]" value="' + item.ledger_expenses + '" type="hidden"/>'
                        str += '<input name="row[' + field_name + '][' + index + '][service_name]" value="' + item.service_name + '" type="hidden"/>'
                        str += '<input name="row[' + field_name + '][' + index + '][standard_price]" value="' + item[types[corporate_type] + '_standard_price'] + '" type="hidden"/>'
                        str += '<input name="row[' + field_name + '][' + index + '][cost_price]" value="' + item[types[corporate_type] + '_cost_price'] + '" type="hidden"/>'
                        str += '<input name="row[' + field_name + '][' + index + '][corporate_type]" value="' + corporate_type + '" type="hidden"/>'
                        index++
                    }
                })
                str += "</table>"
                $('#select-privew').html(str)
                $('.deal_price_ks').change(function () {
                    var index = $(this).attr('index');
                    $('input[bs=' + index + '_collection_price]').val(null)
                    $('input[bs=' + index + '_balance_price]').val(null)
                })
                $('.collection_price_ks').change(function () {
                    var index = $(this).attr('index');
                    var val = $(this).val();
                    var deal_price = $('input[bs=' + index + '_deal_price]').val()
                    if (Number(val) > Number(deal_price)) {
                        $(this).val(deal_price)
                        val = deal_price
                    }
                    $('input[bs=' + index + '_balance_price]').val(deal_price - val)
                })
            }

            Controller.api.bindevent();
        },


        edit: function () {

            const service = Config['service'] || []
            const types = [
                'gth',
                'xgmnsr',
                'ybnsr',
            ]
            $('#c-service').change((e) => {
                rendService()
            })

            function rendService() {
                const value = $('#c-service').val()
                console.log(service)
                console.log(value)
                const corporate_type = Config['corporate_type']
                var index = 0
                const field_name = 'serviceTable'
                var str = '<table border="1" width="100%" style="margin-top: 10px">'
                str += "<tr>"
                str += '<td>服务名称</td>'
                str += '<td>标准价格</td>'
                str += '<td>成交价格</td>'
                str += '<td>服务周期（月）</td>'
                str += '<td>本次收款</td>'
                str += '<td>剩余尾款</td>'
                str += "</tr>"
                service.forEach(item => {
                    if (value.includes(item.id.toString())) {
                        str += "<tr>"
                        str += '<td>' + item.service_name + '</td>'
                        str += '<td>￥' + item[types[corporate_type] + '_standard_price'] + '</td>'
                        str += '<td><input index="' + index + '" bs="' + index + '_deal_price" class="form-control deal_price_ks" value="' + item[types[corporate_type] + '_standard_price'] + '" name="row[' + field_name + '][' + index + '][deal_price]" placeholder="请输入成交价格" data-rule="required;" type="text"/></td>'
                        str += '<td><input index="' + index + '" bs="' + index + '_month" class="form-control" name="row[' + field_name + '][' + index + '][month]" placeholder="服务周期" data-rule="required" type="text"/></td>'
                        str += '<td><input index="' + index + '" bs="' + index + '_collection_price" class="form-control collection_price_ks" name="row[' + field_name + '][' + index + '][collection_price]" placeholder="本次收款" data-rule="required" type="text"/></td>'
                        str += '<td><input index="' + index + '" bs="' + index + '_balance_price" class="form-control balance_price_ks" name="row[' + field_name + '][' + index + '][balance_price]" placeholder="剩余尾款" data-rule="required" type="text"/></td>'
                        str += "</tr>"
                        str += '<input name="row[' + field_name + '][' + index + '][service_id]" value="' + item.id + '" type="hidden"/>'
                        str += '<input name="row[' + field_name + '][' + index + '][ledger_expenses]" value="' + item.ledger_expenses + '" type="hidden"/>'
                        str += '<input name="row[' + field_name + '][' + index + '][service_name]" value="' + item.service_name + '" type="hidden"/>'
                        str += '<input name="row[' + field_name + '][' + index + '][standard_price]" value="' + item[types[corporate_type] + '_standard_price'] + '" type="hidden"/>'
                        str += '<input name="row[' + field_name + '][' + index + '][cost_price]" value="' + item[types[corporate_type] + '_cost_price'] + '" type="hidden"/>'
                        str += '<input name="row[' + field_name + '][' + index + '][corporate_type]" value="' + corporate_type + '" type="hidden"/>'
                        index++
                    }
                })
                str += "</table>"
                $('#select-privew').html(str)
                $('.deal_price_ks').change(function () {
                    var index = $(this).attr('index');
                    $('input[bs=' + index + '_collection_price]').val(null)
                    $('input[bs=' + index + '_balance_price]').val(null)
                })
                $('.collection_price_ks').change(function () {
                    var index = $(this).attr('index');
                    var val = $(this).val();
                    var deal_price = $('input[bs=' + index + '_deal_price]').val()
                    if (Number(val) > Number(deal_price)) {
                        $(this).val(deal_price)
                        val = deal_price
                    }
                    $('input[bs=' + index + '_balance_price]').val(deal_price - val)
                })
            }

            $('.deal_price_ks').change(function () {
                var index = $(this).attr('index');
                $('input[bs=' + index + '_collection_price]').val(null)
                $('input[bs=' + index + '_balance_price]').val(null)
            })
            $('.collection_price_ks').change(function () {
                var index = $(this).attr('index');
                var val = $(this).val();
                var deal_price = $('input[bs=' + index + '_deal_price]').val()
                if (Number(val) > Number(deal_price)) {
                    $(this).val(deal_price)
                    val = deal_price
                }
                $('input[bs=' + index + '_balance_price]').val(deal_price - val)
            })


            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
